package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishDao;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.domain.SetmealDish;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.utils.RedisKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@Transactional
public class DishServiceImpl extends ServiceImpl<DishDao,Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService  categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        System.out.println(dishDto.getName());
        this.save(dishDto);
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().forEach(c->{c.setDishId(id);});
        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
        redisTemplate.delete(RedisKeys.dish+dishDto.getCategoryId()+"_"+dishDto.getStatus());

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //先查询菜单信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        //把dish属性赋值到dishDaoS
        BeanUtils.copyProperties(dish,dishDto);
        //查询口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(lqw);
        dishDto.setFlavors(list);

        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //得到菜品的口味信息
        Long id = dishDto.getId();
        //清理口味信息
        LambdaQueryWrapper<DishFlavor> lwq = new LambdaQueryWrapper<>();
        lwq.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(lwq);
        //再添加新的口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().forEach(c->{c.setDishId(id);});
        dishFlavorService.saveBatch(flavors);
        dishService.updateById(dishDto);
        redisTemplate.delete(RedisKeys.dish+dishDto.getCategoryId()+"_"+dishDto.getStatus());

    }

    @Override
    public void deleteWithFlavor(long[] ids) {
        //批量逻辑删除菜品数组的口味信息
        for (int i = 0; i < ids.length; i++) {
            long id = ids[i];
            LambdaQueryWrapper<DishFlavor>lwq =new LambdaQueryWrapper<>();
            lwq.eq(DishFlavor::getDishId,id);
            //dishFlavorService.remove(lwq);
            List<DishFlavor> list = dishFlavorService.list(lwq);
            list.stream().forEach(c->{
                c.setIsDeleted(1);
            });
            dishFlavorService.updateBatchById(list);
            LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Dish::getId,id);
            //再逻辑删除菜品
            Dish one = dishService.getOne(wrapper);
            one.setIsDeleted(1);
            dishService.updateById(one);
            //再逻辑删除套餐中间表
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getDishId,id);
            List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
            setmealDishes.stream().forEach(c->{
                c.setIsDeleted(1);
            });
            setmealDishService.updateBatchById(setmealDishes);
        }
    }

    @Override
    public void updateStatus(Integer status, long[] ids) {
        //
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Dish::getId,id);
            Dish dish = getOne(wrapper);
            dish.setStatus(status);
            updateById(dish);

        }
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @Override
    public List<DishDto> categoryList(Dish dish) {

        //先从redis中获取缓存数据
        List<DishDto> dtoList = (List<DishDto>) redisTemplate.opsForValue().get(RedisKeys.dish + dish.getCategoryId() + "_" + dish.getStatus());
        if(dtoList==null){
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
            lqw.eq(Dish::getStatus,1);
            lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            lqw.eq(Dish::getIsDeleted,0);
            List<Dish> list = dishService.list(lqw);
            dtoList = new ArrayList<>();
            for (Dish dish1 : list) {
                //塞口味
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish1,dishDto);
                Long dish1Id = dish1.getId();
                LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
                lqw2.eq(DishFlavor::getDishId,dish1Id);
                List<DishFlavor> dishFlavors = dishFlavorService.list(lqw2);
                dishDto.setFlavors(dishFlavors);
                //把菜名塞到菜品里
                Long categoryId = dish1.getCategoryId();
                LambdaQueryWrapper<Category> lwq3= new LambdaQueryWrapper<>();
                lwq3.eq(Category::getId,categoryId);
                Category one = categoryService.getOne(lwq3);
                if(one!=null){
                    dishDto.setCategoryName(one.getName());
                }
                dtoList.add(dishDto);
            }
            //存储到redis中
            redisTemplate.opsForValue().set(RedisKeys.dish + dish.getCategoryId() + "_" + dish.getStatus(),dtoList,60,TimeUnit.MINUTES);
            return dtoList;
        }


        return dtoList;

    }
}